<template>
  <div class="login-container">
    <video
      class="video"
      src="../../assets/bg-video.d2d602a9.mp4"
      muted="muted"
      autoplay="autoplay"
      loop="loop"
    ></video>
    <div class="img1"></div>
    <div class="login-form">
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="login-loginForm"
      >
        <h1 class="title">管理系统</h1>
        <i
          @click="isErwei = !isErwei"
          :class="[
            'jiaobiao',
            'iconfont',
            isErwei ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
          ]"
        ></i>
        <div class="common-login" v-if="!isErwei">
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="loginForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="验证码"
            prop="captche"
            class="el-form-item__content"
          >
            <el-input
              v-model="loginForm.captche"
              maxlength="5"
              class="captcha"
              ref="captcha"
              @keydown.native.enter="submitForm('loginForm')"
            ></el-input>
            <span
              @click="updateCatcha()"
              class="captcha-svg"
              v-html="capthcaSvg"
            ></span>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('loginForm')"
              class="el-button"
              >提交</el-button
            >
          </el-form-item>
        </div>
        <div class="erwei" v-else>
          <div class="img">
            <img :src="getQrUrl" alt="" />
          </div>
          <p>请使用手机微信扫码登入</p>
        </div>
      </el-form>
    </div>
  </div>
</template>


<script>
import * as api from "../../api/index"
import {mapMutations} from "vuex"
import io from "socket.io-client"
import qrcode from "qrcode"
  export default {
    data() {
      var validateCaptche = (rule, value, callback) => {
         if(value.length!==5){
             callback("验证码的长度必须是5位")
         }else{
             callback()
         }
      };
      var validateUsername = (rule, value, callback) => {
        //  var reg = /^\w{3,12}$/
         if(!value){
             callback("用户名可以是字母数字下划线，3-12位")
         }else{
             callback()
         }
      };
      var validatePass = (rule, value, callback) => {
        // var reg =/^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z~!@#$%^&*._?]{8,15}$/
        if(value.length<3){
             callback("密码长度不能小于3")
         }else{
             callback()
         }
      };
      return {
        isErwei:false,
        capthcaSvg:"",
        getQrUrl:"",
        loginForm: {
          username: '',
          password: '',
          captche: ''
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          captche: [
            { validator: validateCaptche, trigger: 'blur' }
          ]
        }
      };
    },
    created(){
         this.updateCatcha()
    },
    methods: {
      ...mapMutations(["SET_USER_INFO"]),
      updateCatcha () {
        api.getCaptchaApi()
        .then(res=>{
          // console.log(res.data);
          this.capthcaSvg = res.data.img;
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            api.verifyCaptchaApi(this.loginForm.captche.toLowerCase())
            .then(res =>{
              // console.log(res.data);
               if(res.data.state){
                  api.loginApi(this.loginForm.username,this.loginForm.password)
                  .then(res =>{
                    // console.log(res.data);
                    if(res.data.state){
                      this.$message.success("登入成功")
                      localStorage.setItem("qf-token",res.data.token);
                      localStorage.setItem("qf-userInfo",JSON.stringify(res.data.userInfo));
                      this.SET_USER_INFO(res.data.userInfo)
                      this.$router.push("/")
                    }else{
                       this.$message.error("账号或者密码输入错误")
                    }
                
                  })
               }else{
                 this.loginForm.captche = ""
                 this.updateCatcha()
                 this.$refs.captcha.focus()
                 this.$message.error("验证码输入错误")
                 
               }
            })
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
    watch:{
      isErwei(newVal,oldVal){
        if(newVal){
          let socket = io("wss://chst.vip")
          // console.log(socket);
          socket.on("connectSuccess",(data)=>{
            let sid = data.sid
            localStorage.setItem("qf-sid",sid)
            api.getQrcodeApi(sid)
            .then(res =>{
              // console.log(res);
              let qrUrl = res.data.scanCodeUrl;
              qrcode.toDataURL(qrUrl,(err,url)=>{
	                if(err) throw err;
	                // console.log(url)
                  this.getQrUrl = url;
               })
            })
            socket.on("scancodeSuccess",(data)=>{
              // console.log(data);
              if(data.state){
               api.getWechatApi(data.wechatCode)
               .then(res =>{
                   if(res.data.state){
                     localStorage.setItem("qf-token",res.data.token);
                     localStorage.setItem("qf-userInfo",JSON.stringify(res.data.userInfo));
                     this.SET_USER_INFO(res.data.userInfo)
                     this.$router.push("/")
                   }else{
                     this.$message.error("微信登入失败")
                   }
               })
              }else{
                this.$message.error("微信扫码失败")
              }
              
          })
          
        })
      }
    }
  }
}
</script>
<style lang="less">
.login-container {
  text-align: center;
  color: #fff;

  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }

  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: -1px;
    top: -1px;
    cursor: pointer;
    opacity: 0.7;
  }

  .img1 {
    background-image: url(../../assets/bg2.fc58c850.png);
    background-repeat: no-repeat;
    position: fixed;
    width: 20%;
    height: 40%;
    background-size: 100% 100%;
    left: 20%;
    top: 40%;
    opacity: 0.5;
  }

  .login-form {
    position: fixed;
    right: 10%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 100px 0 50px 0;
    .captcha {
      width: 100px !important;
      vertical-align: top;
      .el-input {
        position: relative;
        font-size: 14px;
        display: inline-block;
        width: 100%;
      }
      .el-input__inner {
        width: 100%;
        height: 45px;
        border-radius: 5px 0 0 5px;
        border: 0;
        font-size: 18px;
      }
    }

    .img {
      display: inline-block;
      position: relative;
      width: 200px;
      height: 200px;

      img {
        position: absolute;
        left: 0;
        width: 100%;
        height: 100%;
      }
    }
    p {
      display: block;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0px;
      margin-inline-end: 0px;
    }
    .title {
      margin: 0 0 60px 0;
      text-align: center;
      color: #fff;
    }
    .el-form-item {
      padding-right: 50px;
      margin-bottom: 22px;

      .el-button {
        background: linear-gradient(90deg, #1596fb, #002dff);
        width: 250px;
      }
    }

    .captcha-svg {
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 150px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }
    .el-form-item__content {
      width: 250px !important;
    }
  }
}
</style>